﻿using CacheHelper;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using XKPlatform.Common.Const;
using XKPlatform.Common.Extends;
using XKPlatform.DataModels;
using XKPlatform.Common;
using Newtonsoft.Json;

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Text;
using Microsoft.AspNetCore.Http;
using XKPlatform.DataModels.Dao.BaseDao;
using XKPlatform.DataModels.ReturnModel;
using System.Linq;
using XKPlatform.DataModels.ParamsModel;
using XKPlatform.DataModels.SysModel;
using System.Threading.Tasks;
using XKPlatform.Common.Enums;
using XKPlatform.Common.MyAttribute;

namespace XKPlatform.Controllers
{
    public class AdminController : BaseController
    {
        private readonly ICache _cache;
        //  private readonly INoticeService _noticeService;
        private readonly ISysUserService _sysUserService;
        public AdminController(ICache cache, ISysUserService sysUserService, IHttpContextAccessor httpContext) : base(httpContext)
        {
            _cache = cache;
            _sysUserService = sysUserService;
        }




        //#region 保存用户
        //[HttpPost]
        //public JsonResult saveUser(SysUser model)
        //{

        //    QuerySuite querySuite = new QuerySuite("SysUser where UserID!=@UserID and UserNo=@UserNo");
        //    querySuite.AddParam("UserID", model.UserID);
        //    querySuite.AddParam("UserNo", model.UserNo);
        //    if (SqlHelper.Exists(querySuite.countSql, querySuite.Params))
        //        return Json(new { code = 1, msg = "登录账号已存在。" });

        //    //if (!string.IsNullOrEmpty(model.Mobile))
        //    //{
        //    //    querySuite = new QuerySuite("SysUser where UserID!=@UserID and Mobile=@Mobile and RecordStatus=0");
        //    //    querySuite.AddParam("UserID", model.UserID);
        //    //    querySuite.AddParam("Mobile", model.Mobile);
        //    //    if (SqlHelper.Exists(querySuite.countSql, querySuite.Params))
        //    //        return Json(new { code = 2, msg = "手机号码已存在。" });
        //    //}

        //    if (!string.IsNullOrEmpty(model.Email))
        //    {
        //        querySuite = new QuerySuite("SysUser where UserID!=@UserID and Email=@Email and RecordStatus=0");
        //        querySuite.AddParam("UserID", model.UserID);
        //        querySuite.AddParam("Email", model.Email);
        //        if (SqlHelper.Exists(querySuite.countSql, querySuite.Params))
        //            return Json(new { code = 3, msg = "邮箱已存在。" });
        //    }

        //    if (model.UserID == new Guid())
        //    {
        //        string password = GetrandomPassWord();
        //        model.UserID = Guid.NewGuid();
        //        model.CreatedOn = DateTime.Now;
        //        model.CreatedBy = userInfo.UserNo;
        //        model.RecordStatus = false;
        //        model.Password = EncryptHelper.MD5(password);
        //        model.Source = 0;
        //        model.ImportBatch = 0;
        //        if (!userInfo.IsAdmin && !userInfo.IsDev)
        //            model.Org = userInfo.Org;
        //        SqlHelper.InsertSql(model, new string[] { "IsDev", "IsAdmin", "project" });
        //        model.Password = password;
        //        Task.Run(() =>
        //        {
        //            string emailContent = $"<p>Hi</p ><p>您在 XKPlatform系统申请的账号为：【{model.UserNo}】密码为：【{password}】，申请时间：【{DateTime.Now.ToString("yyyy年MM月dd日 HH时mm分ss秒")}】</p ><p><a href=\"https://localhost:4001/views/index.html#/admin/login\" rel=\"noopener\">点击这里访问Coffee Buying Procedure系统</a ></p ><p></p ><p>如果上面的链接无法打开，请复制以下链接至浏览器上 https://localhost:4001/views/index.html#/admin/login </p ><p>如果您没有申请账号，请忽略这封邮件。</p ><p>如有疑问可发送邮件至：service@zysdk.com</p ><p>备注：此邮件为系统自动发送，回复此邮件无效</p ><br>";
        //            //  _noticeService.SendEmailMsg("service@zysdk.com", "service@zysdk.com", new List<string> { model.Email }, "smtp.exmail.qq.com", 25, "service@zysdk.com", "fb7AxX2smXCoPXVY", "Coffee Buying Procedure系统创建账号", emailContent);
        //        });
        //        return Json(new { code = 0, data = model });
        //    }
        //    else
        //    {
        //        model.ModifiedBy = userInfo.UserNo;
        //        model.ModifiedOn = DateTime.Now;

        //        SqlHelper.UpdateSql(model, "UserID", new string[] { "UserNo", "ChangePasswordTime", "LastLoginTime", "Password", "CreatedOn", "CreatedBy", "RecordStatus", "ImportBatch", "QywxUserId", "Openid", "Source", "Org", "IsDev", "IsAdmin", "project" });
        //        return Json(new { code = 0, updateData = model });
        //    }


        //}
        //#endregion

        //        #region 删除用户
        //        [HttpPost]
        //        public JsonResult delUser(string ids)
        //        {
        //            QuerySuite querySuite = new QuerySuite("SysUser");
        //            querySuite.AddParam("UserID", "inid", ids);
        //            querySuite.AddFilter(" and UserNo!='develop'");
        //            SqlHelper.ExecuteSql(querySuite.DeleteSql, querySuite.Params);

        //            SqlHelper.ExecuteSql(@"
        //delete a from SysPostRole a where not EXISTS (select 1 from SysUser where UserNo=a.UserNo) and UserNo is not null
        //delete a from SysPostUserRelevance a where not EXISTS (select 1 from SysUser where UserNo=a.UserNo and a.Org=Org)
        //                    ");


        //            return Json(new { code = 0 });


        //        }
        //        #endregion

        #region 重置密码
        [HttpPost]
        public JsonResult resetUserPassword(Guid? userId)
        {

            string password = GetrandomPassWord();
            var userModel = _sysUserService.GetModel(o => o.UserID == userId);
            if (userModel != null)
            {
                userModel.Password = EncryptHelper.MD5(password);
                userModel.ModifiedBy = userInfo.UserNo;
                userModel.ModifiedOn = DateTime.Now;
                _sysUserService.UpdateModel(userModel, o => o.UserID == userId);
                return Json(new { code = (int)MsgCodeEnum.Success, data = password });
            }
            return Json(new { code = (int)MsgCodeEnum.Failed, msg = EnumUtils.GetEnumDesc(MsgCodeEnum.Failed) });
            //SqlHelper.ExecuteSql("update SysUser set Password=@Password,ChangePasswordTime=null where UserID=@UserID", new SqlParameter[] { new SqlParameter("@Password", EncryptHelper.MD5(password)), new SqlParameter("@UserID", userId) });

            //QuerySuite querySuite = new QuerySuite("SysUser");
            //querySuite.AddParam("UserID", "=", userId);
            //SysUser model = ModelHelper<SysUser>.ConvertToModel(SqlHelper.Query(querySuite.SelectSql, querySuite.Params).Tables[0]);
            //model.Password = password;



        }
        #endregion

        #region 生成随机密码
        public static string GetrandomPassWord()
        {
            return "railway@321";
            //string[] lettr = new string[] { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z" };
            //string[] specialChar = new[] { "!", "@", "*", "_" };
            //List<string> password = new List<string>();
            //try
            //{
            //    Random randmo = new Random();
            //    for (int i = 0; i < 3; i++)
            //    {
            //        int lettrIndex = randmo.Next(0, 25);
            //        int newrandom = randmo.Next(1, 100);
            //        if ((newrandom % 2) == 0)
            //        {
            //            password.Add(lettr[lettrIndex]);
            //        }
            //        else
            //        {
            //            password.Add(lettr[lettrIndex].ToUpper());
            //        }
            //        int specialCharIndex = randmo.Next(0, 3);
            //        password.Add(specialChar[specialCharIndex]);
            //        int randomNum = randmo.Next(0, 9);
            //        password.Add(randomNum.ToString());

            //    }
            //    password.Add(lettr[randmo.Next(1, 25)]);
            //    string newPassWord = "";
            //    password.ForEach(m => newPassWord += m);
            //    return newPassWord;
            //}
            //catch (Exception)
            //{
            //    return "Nestle@defult123";
            //}
        }
        #endregion

        #region 同步企业微信用户  
        public JsonResult SysnUser()
        {
            var res = WeixinHelper.QywxSync();
            if (res == true)
            {
                return Json(new { code = 0 });
            }
            else
            {
                return Json(new { code = -1 });
            }
        }
        #endregion

        #region 同步区域
        public JsonResult SysnOrg()
        {
            SqlHelper.ExecuteSql(@"

update b set b.Org = a.OrgNo from SysOrg a,SysDepartment b where a.DepartmentNo = b.DepartmentNo and a.OrgNo is not null and a.RecordStatus = 0
update b set b.Org = a.Org from SysDepartment a,SysUser b where a.DepartmentID = b.DepartmentID and a.Org is not null and a.RecordStatus = 0
");
            return Json(new { code = 0 });
        }
        #endregion

        #region 同步企业微信用户  
        public JsonResult SysnOpenid()
        {
            var res = WeixinHelper.OpenidSync();
            if (res == true)
            {
                return Json(new { code = 0 });
            }
            else
            {
                return Json(new { code = -1 });
            }
        }
        #endregion





        #region 修改密码
        [HttpPost]
        public JsonResult updateUserPassword(string oldPassword, string newPassword)
        {

            // oldPassword = "34a52430d64eea0b72a4414d0cfa5571";
            // newPassword = "34a52430d64eea0b72a4414d0cfa5571";
            //QuerySuite querySuite = new QuerySuite("SysUser where UserNo=@UserNo and Password=@Password and RecordStatus=0");
            //querySuite.AddParam("UserNo", userInfo.UserNo);
            //querySuite.AddParam("Password", oldPassword);

            var userModel = _sysUserService.GetModel(o => o.UserNo == userInfo.UserNo && o.Password == oldPassword);// ModelHelper<SysUser>.ConvertToModel(SqlHelper.Query(querySuite.SelectSql, querySuite.Params).Tables[0]);
            if (userModel == null)
                return Json(new { code = 1, msg = "旧密码不正确。" });

          //  SqlHelper.ExecuteSql("update SysUser set Password=@Password,LastLoginTime=getdate(),ChangePasswordTime=getdate() where UserNo=@UserNo  and RecordStatus=0", new SqlParameter[] { new SqlParameter("@Password", newPassword), new SqlParameter("@UserNo", userInfo.UserNo) });
            userModel.LastLoginTime = DateTime.Now;
            userModel.ChangePasswordTime = DateTime.Now;
            userModel.Password = newPassword;
            _sysUserService.UpdateModel(userModel,o=>o.UserNo==userInfo.UserNo&&o.RecordStatus==false);
            return Json(new { code = 0 });

        }
        #endregion

        #region 系统角色

        #region 获取角色列表
        public JsonResult getRoleList(Search search)
        {

            QuerySuite querySuite = new QuerySuite("SysRole", search);

            // if (!userInfo.IsDev)
            // querySuite.AddParam("RoleID", "notinid", "ebf7bf27-3892-4f6d-899e-a484faaaf2b4,27aebc85-021b-466a-836e-6f9c29a1b46d");

            //if (!userInfo.IsDev && !userInfo.IsAdmin)
            //{
            //    querySuite.AddParam("RoleID", "notinid", MemoryCacheHelper.getDictionaryCache("SysAdminRole"));
            //    querySuite.AddFilter(" and(Org=@Org or (Org is null and ','+@SysAreaAdminRole+',' like '%,' + Cast(RoleID As nvarchar(36)) + ',%')) ");
            //    querySuite.AddParam("Org", userInfo.Org);
            //    querySuite.AddParam("SysAreaAdminRole", MemoryCacheHelper.getDictionaryCache("SysAreaAdminRole"));
            //}

            DataSet ds = SqlHelper.Query(querySuite.LimitSql, querySuite.Params);

            return Json(new { code = 0, data = QuerySuite.ToDictionary(ds.Tables[0]), count = QuerySuite.DsCount(ds) });

        }

        public JsonResult getRoleSetList(Search search)
        {
            QuerySuite querySuite = new QuerySuite("SysRole a left join SysProjectRole b on a.RoleID=b.RoleID", search);

            if (userInfo.project.ToUpper() != "")
            {
                querySuite.AddParam("ProjectID", "=", userInfo.project);
            }

            //if (!userInfo.IsDev)
            //{
            //    querySuite.AddParam("RoleID", "notinid", "ebf7bf27-3892-4f6d-899e-a484faaaf2b4,27aebc85-021b-466a-836e-6f9c29a1b46d");
            //    querySuite.AddParam("RoleID", "notinid", MemoryCacheHelper.getDictionaryCache("SysAdminRole"));
            //}

            //if (!userInfo.IsDev && !userInfo.IsAdmin)
            //    querySuite.AddParam("Org", "=", userInfo.Org);

            DataSet ds = SqlHelper.Query(querySuite.LimitSql, querySuite.Params);

            return Json(new { code = 0, data = QuerySuite.ToDictionary(ds.Tables[0]), count = QuerySuite.DsCount(ds) });

        }
        #endregion

        #region 获取角色下拉列表
        public JsonResult getRoleSelect(Search search)
        {

            QuerySuite querySuite = new QuerySuite("SysRole", "RoleID,RoleName,RoleName_EN", search);
            //if (userInfo.IsAdmin)
            //{
            //    querySuite.AddParam("RoleID", "notinid", "ebf7bf27-3892-4f6d-899e-a484faaaf2b4,27aebc85-021b-466a-836e-6f9c29a1b46d");
            //    querySuite.AddFilter(" and(Org is null or ','+@SysAreaAdminRole+',' like '%,' + Cast(RoleID As nvarchar(36)) + ',%' or ','+@SysAdminRole+',' like '%,' + Cast(RoleID As nvarchar(36)) + ',%') ");

            //    querySuite.AddParam("SysAdminRole", MemoryCacheHelper.getDictionaryCache("SysAdminRole"));
            //}
            //if (!userInfo.IsDev)
            //{
            //    querySuite.AddParam("RoleID", "notinid", "ebf7bf27-3892-4f6d-899e-a484faaaf2b4,27aebc85-021b-466a-836e-6f9c29a1b46d");
            //    querySuite.AddParam("RoleID", "notinid", MemoryCacheHelper.getDictionaryCache("SysAdminRole"));

            //    querySuite.AddFilter(" and(Org=@Org or (Org is null and ','+@SysAreaAdminRole+',' like '%,' + Cast(RoleID As nvarchar(36)) + ',%')) ");
            //}

            //querySuite.AddParam("Org", userInfo.Org);
            //querySuite.AddParam("SysAreaAdminRole", MemoryCacheHelper.getDictionaryCache("SysAreaAdminRole"));

            //if (!userInfo.IsDev)
            //    querySuite.AddParam("RoleID", "notinid", "ebf7bf27-3892-4f6d-899e-a484faaaf2b4,27aebc85-021b-466a-836e-6f9c29a1b46d");

            //if (!userInfo.IsDev && !userInfo.IsAdmin)
            //{
            //    querySuite.AddParam("RoleID", "notinid", MemoryCacheHelper.getDictionaryCache("SysAdminRole"));
            //    querySuite.AddFilter(" and(Org=@Org or (Org is null and ','+@SysAreaAdminRole+',' like '%,' + Cast(RoleID As nvarchar(36)) + ',%')) ");
            //    querySuite.AddParam("Org", userInfo.Org);
            //    querySuite.AddParam("SysAreaAdminRole", MemoryCacheHelper.getDictionaryCache("SysAreaAdminRole"));
            //}

            DataSet ds = SqlHelper.Query(querySuite.LimitSql, querySuite.Params);

            return Json(new { code = 0, data = QuerySuite.ToDictionary(ds.Tables[0]), count = QuerySuite.DsCount(ds) });

        }
        #endregion

        #region 获取角色操作权限列表
        public JsonResult getRolePageList(Guid? RoleID, Search search)
        {

            QuerySuite querySuite = new QuerySuite("SysPage a left join SysRolePage b on a.PageID=b.PageID and b.RoleID=@RoleID left join SysProject c on a.ProjectID=c.ProjectNo where No=@No or ParentID is null", "distinct a.PageID,a.ParentID,a.PageName,a.PageName_EN,a.PageType,OrderNo,case when b.PageID is not null then 1 else 0 end lay_is_checked ", search);
            querySuite.AddParam("RoleID", RoleID);
            if (userInfo.project.ToUpper() != "")
            {
                querySuite.AddParam("No", userInfo.project);
            }
            if (userInfo.DefaultRoleID.ToString().ToUpper() == HttpContextCore.developID)
            {
                querySuite.AddFilter(" or ProjectID='000'");
            }
            //if (!userInfo.IsDev)
            //{
            //    querySuite = new QuerySuite("SysPage a join SysRolePage a1 on a.PageID=a1.PageID left join SysRolePage b on a.PageID=b.PageID and b.RoleID=@RoleID", "distinct a.PageID,a.ParentID,a.PageName,a.PageName_EN,a.PageType,OrderNo,case when b.PageID is not null then 1 else 0 end lay_is_checked ", search);
            //    querySuite.AddParam("a1.RoleID", "inid", userInfo.Roles);
            //    querySuite.AddParam("RoleID", RoleID);
            //}

            DataSet ds = SqlHelper.Query(querySuite.LimitSql, querySuite.Params);

            return Json(new { code = 0, data = QuerySuite.ToDictionary(ds.Tables[0]), count = QuerySuite.DsCount(ds) });

        }
        #endregion

        #region 保存角色
        /// <summary>
        /// 如果是管理员 开发运维角色，将角色添加到角色池中。给角色分配项目后，登陆该项目可以看到此角色、、
        /// 如果是普通用户，则增加角色到本项目中
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        //[HttpPost]
        //public JsonResult saveRole(SysRole model)
        //{


        //    //QuerySuite querySuite = new QuerySuite("SysRole where RoleID!=@RoleID and (RoleName=@RoleName or RoleName_EN=@RoleName_EN)");
        //    //querySuite.AddParam("RoleID", model.RoleID);
        //    //querySuite.AddParam("RoleName", model.RoleName);
        //    //querySuite.AddParam("RoleName_EN", model.RoleName_EN);

        //    //if (!userInfo.IsDev && !userInfo.IsAdmin)
        //    //    querySuite.AddParam("Org", "=", userInfo.Org);

        //    //if (SqlHelper.Exists(querySuite.countSql, querySuite.Params))
        //    //    return Json(new { code = 1, msg = "角色已存在。" });

        //    //if (model.RoleID == (new Guid()))
        //    //{
        //    //    model.RoleID = Guid.NewGuid();
        //    //    model.CreatedOn = DateTime.Now;
        //    //    model.CreatedBy = userInfo.UserNo;
        //    //    model.RecordStatus = false;

        //    //    if (!userInfo.IsDev && !userInfo.IsAdmin)
        //    //    {
        //    //        model.Org = userInfo.Org;
        //    //    }



        //    //    SqlHelper.InsertSql(model);

        //    //    //新增角色时，保存当前项目下
        //    //    SqlHelper.ExecuteInsertSql($"insert into SysProjectRole (RoleID,ProjectID) values ('{model.RoleID.ToString()}', '{userInfo.project.ToUpper()}' )");
        //    //}
        //    //else
        //    //{
        //    //    model.ModifiedBy = userInfo.UserNo;
        //    //    model.ModifiedOn = DateTime.Now;
        //    //    SqlHelper.UpdateSql(model, "RoleID", new string[] { "CreatedOn", "CreatedBy", "RecordStatus", "Org" });
        //    //}

        //    //return Json(new { code = 0, updateData = model });

        //}
        #endregion

        #region 删除角色
        /// <summary>
        /// 从sysrole 表中删除角色 物理删除
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult delRoleFromRoleTable(string ids)
        {
            QuerySuite querySuite = new QuerySuite("SysRole");
            querySuite.AddParam("RoleID", "inid", ids);
            if (!userInfo.IsDev && !userInfo.IsAdmin)
                querySuite.AddParam("Org", "=", userInfo.Org);

            SqlHelper.ExecuteSql(querySuite.DeleteSql, querySuite.Params);

            querySuite = new QuerySuite("SysRolePage");
            querySuite.AddParam("RoleID", "inid", ids);
            if (!userInfo.IsDev && !userInfo.IsAdmin)
                querySuite.AddParam("Org", "=", userInfo.Org);


            SqlHelper.ExecuteSql(querySuite.DeleteSql, querySuite.Params);
            return Json(new { code = 0 });


        }
        /// <summary>
        /// 只删除角色和项目的关联关系
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult delRole(string ids)
        {
            //QuerySuite querySuite = new QuerySuite("SysRole");
            //querySuite.AddParam("RoleID", "inid", ids);
            ////if (!userInfo.IsDev && !userInfo.IsAdmin)
            ////    querySuite.AddParam("Org", "=", userInfo.Org);

            //SqlHelper.ExecuteSql(querySuite.DeleteSql, querySuite.Params);

            QuerySuite querySuite = new QuerySuite("SysProjectRole");
            querySuite.AddParam("RoleID", "inid", ids);
            querySuite.AddParam("ProjectID", "inid", userInfo.project);
            SqlHelper.ExecuteSql(querySuite.DeleteSql, querySuite.Params);

            querySuite = new QuerySuite("SysRolePage");
            querySuite.AddParam("RoleID", "inid", ids);
            //if (!userInfo.IsDev && !userInfo.IsAdmin)
            //    querySuite.AddParam("Org", "=", userInfo.Org);


            SqlHelper.ExecuteSql(querySuite.DeleteSql, querySuite.Params);

            return Json(new { code = 0 });

        }
        #endregion

        #region 保存角色操作权限
        [HttpPost]
        public JsonResult saveRolePage(Guid? RoleID, string Roles)
        {
            SqlHelper.ExecuteSql("delete SysRolePage where RoleID=@RoleID", new SqlParameter("@RoleID", RoleID));

            if (!string.IsNullOrEmpty(Roles))
                SqlHelper.ExecuteSql("insert into SysRolePage select @RoleID,PageID from SysPage where ','+@Roles+',' like '%,'+cast(PageID as nvarchar(36))+',%'", new SqlParameter[] { new SqlParameter("@RoleID", RoleID), new SqlParameter("@Roles", Roles) });


            return Json(new { code = 0 });


        }
        #endregion

        #endregion

        #region 角色分配

        #region 获取用户列表（显示角色名称） 
        public JsonResult getUserListRoles(Search search)
        {

            var fields = QuerySuite.GetTableFieldsSql<SysUser>(new string[] { "Remarks", "CreatedBy", "CreatedOn", "ModifiedBy", "ModifiedOn", "OrderNo", "RecordStatus", "ImportBatch" });


            QuerySuite querySuite = new QuerySuite(@"(select a.*,b.DepartmentName,b.DepartmentFullName,d.PostName,
                    stuff((select ','+PostName from SysPost b,SysPostUserRelevance c where b.PostNo=c.PostNo and c.UserNo = a.UserNo ORDER BY b.OrderNo for xml path('')),1,1,'') PostsName,
                    c.Roles,stuff((select ','+RoleName from SysRole where ','+isnull(c.Roles,'')+',' like '%,'+ Cast(RoleID As nvarchar(36))+',%' ORDER BY OrderNo for xml path('')),1,1,'') RolesName
                    from SysUser a left join SysDepartment b on a.DepartmentNo=b.DepartmentNo and b.RecordStatus=0 and a.Org=b.Org
                    left join SysPostRole c on a.UserNo=c.UserNo and a.Org=c.Org
					left join SysPost d on a.PostNo = d.PostNo and d.RecordStatus = 0 and a.Org=d.Org
                    where a.RecordStatus=0) t", fields + ",DepartmentName,DepartmentFullName,PostName,PostsName,Roles,RolesName", search);

            if (!userInfo.IsAdmin && !userInfo.IsDev)
                querySuite.AddParam("Org", "=", userInfo.Org);

            DataSet ds = SqlHelper.Query(querySuite.LimitSql, querySuite.Params);

            return Json(new { code = 0, data = QuerySuite.ToDictionary(ds.Tables[0]), count = QuerySuite.DsCount(ds) });

        }
        #endregion

        #region 获取岗位列表（显示角色名称）
        //public JsonResult getPostListRoles(Search search)
        //{
        //    try
        //    {
        //        QuerySuite querySuite = new QuerySuite(@"(select a.*,
        //        b.Roles,stuff((select ','+RoleName from SysRole where ','+isnull(b.Roles ,'')+',' like '%,'+ Cast(RoleID As nvarchar(36))+',%' ORDER BY OrderNo for xml path('')),1,1,'') RolesName
        //        from SysPost a left join SysPostRole b on a.PostNo = b.PostNo where a.RecordStatus = 0 ) t", search);

        //        //QuerySuite querySuite = new QuerySuite(@"SysPost where RecordStatus = 0", search);


        //        //if (querySuite.CustomList.Count > 0)
        //        //{
        //        //    foreach (var item in querySuite.CustomList)
        //        //    {
        //        //        if (item.Compare == "PostType")
        //        //        {
        //        //            querySuite.AddFilter(" and PostType in (" + item.SearchValue + ")");
        //        //        }

        //        //    }
        //        //}

        //        DataSet ds = SqlHelper.Query(querySuite.LimitSql, querySuite.Params);

        //        return Json(new { code = 0, data = QuerySuite.ToDictionary(ds.Tables[0]), count = QuerySuite.DsCount(ds) });
        //    }
        //    catch (Exception e)
        //    {
        //        LogHelper.SaveLog(e);
        //        return Json(new { code = -1 });
        //    }
        //}

        #endregion



        #region 保存用户角色
        //public JsonResult saveUserRole(SysPostRole model)
        //{

        //    if (string.IsNullOrEmpty(userInfo.Org))
        //        return Json(new { code = 9, msg = "当前用户无区域划分，无法执行保存" });

        //    if (model.Org == null)
        //        return Json(new { code = 9, msg = "区域信息为空,无法执行" });

        //    SqlHelper.ExecuteSql("delete SysPostRole where UserNo=@UserNo", new SqlParameter[] { new SqlParameter("@UserNo", model.UserNo) });
        //    SqlHelper.ExecuteSql(" delete from sysLoginAccessToken where UserId = (select UserID from SysUser where UserNo =@UserNo)", new SqlParameter[] { new SqlParameter("@UserNo", model.UserNo) });
        //    model.ID = Guid.NewGuid();
        //    model.PostNo = null;

        //    SqlHelper.InsertSql(model);

        //    return Json(new { code = 0 });


        //}
        #endregion

        #endregion

        #region 获取字典列表
        public JsonResult getDictionaryList(Search search)
        { 
            return Json(new { code = 0, data = "", count = 0 });

        }
        #endregion

        #region 获取字典下拉列表
        //[AllowAnonymous]
        public JsonResult getDictionarySelect(Search search)
        { 

            return Json(new { code = 0, data = "", count = 0 });

        }
        #endregion

        #region 获取字典参数列表
        //public JsonResult getGroupDictionaryList(Search search)
        //{
        //    try
        //    {

        //        QuerySuite querySuite = new QuerySuite("(select a.*,b.MemberName TypeName from SysDictionary a left join SysDictionary b on a.ParentID=b.DictionaryID and b.RecordStatus=0 where a.RecordStatus=0  ) t", search);


        //        DataSet ds = SqlHelper.Query(querySuite.LimitSql, querySuite.Params);

        //        return  Json(new { code = 0, data = QuerySuite.ToDictionary(ds.Tables[0]), count = QuerySuite.DsCount(ds) });
        //    }
        //    catch (Exception e)
        //    {
        //        LogHelper.SaveLog(e);
        //        return Json(new { code = -1 } );
        //    }
        //}

        #endregion
  
         

        #region 清空列表
        [HttpPost]
        public JsonResult clearWord()
        {
            SqlHelper.ExecuteSql("delete a from SysDictionary a,SysDictionary b where a.ParentID=b.DictionaryID and b.Type='WordType' and a.RecordStatus=0 and b.RecordStatus=0");

            return Json(new { code = 0 });

        }
        #endregion


        #region 菜单管理

        #region 获取菜单列表
        public JsonResult getPageList(Search search)
        {
            var fields = "PageID,ParentID,PageName,PageName_EN,Sign,TemplateUrl,PageUrl,PageType,ActionUrl,AreaCols,AreaType,PageIcon,OrderNo,CreatedBy,CreatedOn,OS,IsHide,ProjectID";

            QuerySuite querySuite = new QuerySuite("SysPage ", fields, search);

            if (search.SearchWhere == null)
                querySuite.AddFilter("and ParentID is null");

            if (querySuite.CustomList.Count > 0)
            {
                foreach (var item in querySuite.CustomList)
                {
                    if (item.Compare == "ParentID")
                    {
                        querySuite = new QuerySuite("CTE a left join  SysProject b on a.ProjectID=b.ProjectNo where 1=1 ", search);//No = @No or ProjectID = '000'

                        string cte = @"WITH CTE AS 
                                    (
                                    SELECT * FROM SysPage WHERE PageID=@PageID 
                                    UNION ALL 
                                    SELECT a.* from SysPage a INNER JOIN CTE b ON a.ParentID=b.PageID
                                    )";
                        querySuite.AddParam("PageID", item.SearchValue);

                        querySuite.Cte = cte;
                        //if (userInfo.project.ToUpper() != "")
                        //{
                        //    querySuite.AddParam("No", userInfo.project);
                        //}
                    }
                }
            }

            DataSet ds = SqlHelper.Query(querySuite.LimitSql, querySuite.Params);

            return Json(new { code = 0, data = QuerySuite.ToDictionary(ds.Tables[0]), count = QuerySuite.DsCount(ds) });

        }

        #region 获取菜单下拉列表
        public JsonResult getPageSelect(Search search)
        {
            QuerySuite querySuite = new QuerySuite("SysPage", "PageID,PageName,PageName_EN", search);

            DataSet ds = SqlHelper.Query(querySuite.LimitSql, querySuite.Params);

            return Json(new { code = 0, data = QuerySuite.ToDictionary(ds.Tables[0]), count = QuerySuite.DsCount(ds) });

        }
        #endregion

        #endregion

        #region 保存菜单
        [HttpPost]
        public JsonResult savePage(SysPage model)
        {
            if (model.PageID == new Guid())
            {
                model.PageID = Guid.NewGuid();
                //if (!model.ParentID.HasValue)
                //    model.OS = model.PageName_EN;
                SqlHelper.InsertSql(model);
                string sql = string.Format("insert into SysProjectPage(PageID,proID) values('{0}','{1}')", model.PageID, model.ProjectID);
                SqlHelper.ExecuteSql(sql);
            }
            else
            {
                if (!model.ParentID.HasValue)
                    model.OS = DBNull.Value.ToString();
                SqlHelper.UpdateSql(model, "PageID", new string[] { "CreatedOn", "CreatedBy", "RecordStatus" });
                string sql = string.Format("update SysProjectPage set proID='{0}' where PageID='{1}'", model.ProjectID, model.PageID);
                if (SqlHelper.ExecuteSql(sql) == 0)
                {
                    string insertsql = string.Format("insert into SysProjectPage(PageID,proID) values('{0}','{1}')", model.PageID, model.ProjectID);
                    SqlHelper.ExecuteSql(insertsql);
                }
            }

            if (!model.ParentID.HasValue)
            {
                QuerySuite querySuite = new QuerySuite("SysPage a,CTE b where a.PageID=b.PageID");

                string cte = @"WITH CTE AS 
                                    (
                                    SELECT * FROM SysPage WHERE PageID=@PageID
                                    UNION ALL 
                                    SELECT a.* from SysPage a INNER JOIN CTE b ON a.ParentID=b.PageID
                                    )";

                querySuite.AddParam("PageID", model.PageID);
                querySuite.AddParam("OS", model.PageName_EN);

                SqlHelper.ExecuteSql(cte + "update a set a.OS=@OS from " + querySuite.FromSql, querySuite.Params);
            }
            if (model.ParentID.HasValue)
            {
                QuerySuite querySuite = new QuerySuite("SysPage a,CTE b,SysPage c where a.PageID=b.PageID and c.PageID=@ParentID");

                string cte = @"WITH CTE AS 
                                    (
                                    SELECT * FROM SysPage WHERE PageID=@PageID
                                    UNION ALL 
                                    SELECT a.* from SysPage a INNER JOIN CTE b ON a.ParentID=b.PageID
                                    )";

                querySuite.AddParam("PageID", model.PageID);
                querySuite.AddParam("ParentID", model.ParentID);

                SqlHelper.ExecuteSql(cte + "update a set a.OS=isnull(c.OS,c.PageName_EN) from " + querySuite.FromSql, querySuite.Params);
            }

            return Json(new { code = 0, updateData = model });


        }
        #endregion

        #region 删除菜单
        [HttpPost]
        public JsonResult delPage(string ids)
        {
            string rootWhere = "',' + @PageID + ',' like '%,' + Cast(PageID As nvarchar(36)) + ',%'";
            string cte = @"WITH CTE AS 
                                    (
                                    SELECT * FROM SysPage WHERE {0}
                                    UNION ALL 
                                    SELECT a.* from SysPage a INNER JOIN CTE b ON a.ParentID=b.PageID
                                    )";

            QuerySuite querySuite = new QuerySuite("SysPage a join CTE b on a.PageID=b.PageID");
            querySuite.AddParam("PageID", ids);
            SqlHelper.ExecuteSql(string.Format(cte, rootWhere) + "delete a from " + querySuite.FromSql, querySuite.Params);

            querySuite = new QuerySuite("SysRolePage a join CTE b on a.PageID=b.PageID");
            querySuite.AddParam("PageID", ids);
            SqlHelper.ExecuteSql(string.Format(cte, rootWhere) + "delete a from " + querySuite.FromSql, querySuite.Params);

            return Json(new { code = 0 });

        }
        #endregion

        #endregion

        #region 错误日志

        #region 获取错误日志列表
        public JsonResult getErrorLogList(Search search)
        {
            QuerySuite querySuite = new QuerySuite(@"SysLog where RecordStatus=0", search);

            DataSet ds = SqlHelper.Query(querySuite.LimitSql, querySuite.Params);

            return Json(new { code = 0, data = QuerySuite.ToDictionary(ds.Tables[0]), count = QuerySuite.DsCount(ds) });

        }
        #endregion

        #region 删除日志
        [HttpPost]
        public JsonResult delErrorLog(string ids)
        {
            QuerySuite querySuite = new QuerySuite("SysLog");
            querySuite.AddParam("LogID", "inid", ids);
            SqlHelper.ExecuteSql(querySuite.DeleteSql, querySuite.Params);

            return Json(new { code = 0 });


        }
        #endregion  

        #region 清空日志
        [HttpPost]
        public JsonResult clearErrorLog()
        {
            SqlHelper.ExecuteSql("delete SysLog");

            return Json(new { code = 0 });

        }
        #endregion

        #endregion  

        #region 获取API下拉列表g
        public JsonResult getRoleitem(Search search)
        {
            //var fields = "a.RoleID as roleId,RoleName as role,ProjectID as ProId";

            //QuerySuite querySuite = new QuerySuite("SysRole a left join SysProjectRole b on a.RoleID=b.RoleID where ProjectID=@ProjectID", fields, search);
            //if (userInfo.project.ToUpper() != "")
            //{
            //    querySuite.AddParam("ProjectID", userInfo.project);
            //}
            //DataSet ds = SqlHelper.Query(querySuite.LimitSql, querySuite.Params);

            //return Json(new { code = 0, data = QuerySuite.ToDictionary(ds.Tables[0]), count = QuerySuite.DsCount(ds) });


            QuerySuite querySuite = new QuerySuite("SysRole a left join SysProjectRole b on a.RoleID=b.RoleID");
            querySuite.Order = "RoleName";
            if (userInfo.project.ToUpper() != "")
            {
                querySuite.AddParam("ProjectID", "=", userInfo.project);
            }

            DataSet ds = SqlHelper.Query(querySuite.LimitSql, querySuite.Params);

            DataSet users = SqlHelper.Query("SELECT * FROM  SysUser where RecordStatus =0");
            List<SysUser> userlist = ModelHelper<SysUser>.ConvertToModelList(users.Tables[0]);
            List<dynamic> list = new List<dynamic>();
            for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
            {
                dynamic model = new
                {
                    ID = ds.Tables[0].Rows[i]["RoleID"].ToString(),
                    Name = ds.Tables[0].Rows[i]["RoleName"].ToString(),
                    Type = 1,
                    ParentId = ""
                };
                list.Add(model);
                foreach (var item in userlist)
                {
                    if (item.DefaultRoleID.ToString() == ds.Tables[0].Rows[i]["RoleID"].ToString())
                    {
                        model = new
                        {
                            ID = item.UserID,
                            Name = item.UserName,
                            Type = 2,
                            ParentId = ds.Tables[0].Rows[i]["RoleID"].ToString()
                        };
                        list.Add(model);
                    }
                }
            }

            return Json(new { code = 0, data = list });

        }

        public JsonResult geRoleAPIList(Guid? ProId, Guid? ID, int Type, Search search)
        {

            string fields = "distinct a.ID,d.ProjectName  as ProId,a.ApiName,a.UrlAddr";

            QuerySuite querySuite = new QuerySuite("sysApi a left join SysProjectApi c on a.ID=c.ApiId left join SysProject d on c.ProId=d.No where 1=1 ", fields, search);

            querySuite.AddFilter("and c.ProId =@ProId or c.ProId='00000000-0000-0000-0000-000000000000'");
            querySuite.AddParam("ProId", userInfo.project);


            DataSet ds = SqlHelper.Query(querySuite.SelectSql, querySuite.Params);

            List<RoleUserAPIReturn> list = ModelHelper<RoleUserAPIReturn>.ConvertToModelList(ds.Tables[0]);
            BaseFreeSqlDao<RoleAPIMappingModel> roleAPIMappingDao = new BaseFreeSqlDao<RoleAPIMappingModel>();
            List<RoleAPIMappingModel> roleAPIMappingModels = new List<RoleAPIMappingModel>();
            if (Type == 1)
            {
                roleAPIMappingModels = roleAPIMappingDao.GetList(t => t.Type == 1 && t.RoleId == ID.ToString());
            }
            else if (Type == 2)
            {
                roleAPIMappingModels = roleAPIMappingDao.GetList(t => t.Type == 1 && t.UserId == ID.ToString());
            }

            foreach (var item in list)
            {
                if (roleAPIMappingModels.Any(t => t.ApiId.ToLower() == item.ID.ToString().ToLower()))
                {
                    item.lay_is_checked = 1;
                }
            }

            return Json(new { code = 0, data = list, count = QuerySuite.DsCount(ds) });

        }



        public JsonResult getAPIList()
        {
            string filed = "ApiName";
            QuerySuite querySuite = new QuerySuite("sysApi where RecordStatus=0", filed);
            DataSet ds = SqlHelper.Query(querySuite.SelectSql, querySuite.Params);

            return Json(new { code = 0, data = QuerySuite.ToDictionary(ds.Tables[0]) });

        }
        //获取项目
        public JsonResult getProjectList()
        {
            string filed = "ProjectName,No";
            QuerySuite querySuite = new QuerySuite("SysProject where RecordStatus=0", filed);
            DataSet ds = SqlHelper.Query(querySuite.SelectSql, querySuite.Params);
            DataRow dataRow = ds.Tables[0].NewRow();
            dataRow["No"] = "00000000-0000-0000-0000-000000000000";
            dataRow["ProjectName"] = "All";
            ds.Tables[0].Rows.Add(dataRow);
            return Json(new { code = 0, data = QuerySuite.ToDictionary(ds.Tables[0]) });

        }

        public JsonResult saveroleapi(Guid? ID, int Type, string Roles)
        {
            if (Type == 1)
            {
                SqlHelper.ExecuteSql("delete RoleAPIMapping where RoleId=@RoleID and Type = 1", new SqlParameter("@RoleID", ID));
            }
            else if (Type == 2)
            {
                SqlHelper.ExecuteSql("delete RoleAPIMapping where UserId=@UserId and Type = 1", new SqlParameter("@UserId", ID));
            }
            if (!string.IsNullOrEmpty(Roles))
                if (Type == 1)
                {
                    SqlHelper.ExecuteSql($"insert into RoleAPIMapping select NEWID(),@RoleID,RoleName,Id,UrlAddr,ApiName,'0',getdate(),null,null,null,null,null,1 from SysRole a,sysApi b where a.RoleID=@RoleID and b.ApiName in({ConvertToSqlInStr(Roles.Split(','))})", new SqlParameter[] { new SqlParameter("@RoleID", ID) });
                }
                else if (Type == 2)
                {
                    SqlHelper.ExecuteSql($"insert into RoleAPIMapping select NEWID(),null,null,Id,UrlAddr,ApiName,'0',getdate(),null,null,null,@UserId,UserName,1 from SysUser a,sysApi b where a.UserID=@UserId and b.ApiName in({ConvertToSqlInStr(Roles.Split(','))})", new SqlParameter[] { new SqlParameter("@UserId", ID) });
                }


            return Json(new { code = 0 });


        }
        #endregion

        #region
        public JsonResult SaveProject(string proid)
        {
            string sql = string.Format("select top 1 No from SysProject where ProjectNo='{0}'", proid);
            DataSet ds = SqlHelper.Query(sql);
            if (ds.Tables[0].Rows.Count > 0)
            {
                userInfo.project = ds.Tables[0].Rows[0]["No"].ToString();
            }
            return Json(new { code = 0 });
        }
        #endregion
        #region 获取项目
        public JsonResult getProjectSetList(Search search)
        {

            QuerySuite querySuite = new QuerySuite("SysProject", search);
            querySuite.AddParam("RecordStatus", "inid", "0");
            //if (!userInfo.IsDev)
            //{
            //    querySuite.AddParam("RoleID", "notinid", "ebf7bf27-3892-4f6d-899e-a484faaaf2b4,27aebc85-021b-466a-836e-6f9c29a1b46d");
            //    querySuite.AddParam("RoleID", "notinid", MemoryCacheHelper.getDictionaryCache("SysAdminRole"));
            //}

            //if (!userInfo.IsDev && !userInfo.IsAdmin)
            //    querySuite.AddParam("Org", "=", userInfo.Org);

            DataSet ds = SqlHelper.Query(querySuite.LimitSql, querySuite.Params);
            DataRow dataRow = ds.Tables[0].NewRow();
            dataRow["ProjectNo"] = "000";
            dataRow["ProjectName"] = "All";
            ds.Tables[0].Rows.Add(dataRow);
            return Json(new { code = 0, data = QuerySuite.ToDictionary(ds.Tables[0]), count = QuerySuite.DsCount(ds) });

        }
        #endregion
        #region 保存项目分配角色
        [HttpPost]
        public JsonResult saveRoleProject(string ProjectID, string Roles)
        {
            SqlHelper.ExecuteSql("delete SysProjectRole where ProjectID=@ProjectID", new SqlParameter("@ProjectID", ProjectID));

            //if (!string.IsNullOrEmpty(Roles))
            // SqlHelper.ExecuteSql("insert into SysRolePage select @RoleID,PageID from SysPage where ','+@Roles+',' like '%,'+cast(PageID as nvarchar(36))+',%'", new SqlParameter[] { new SqlParameter("@RoleID", RoleID), new SqlParameter("@Roles", Roles) });
            if (!string.IsNullOrEmpty(Roles))
                SqlHelper.ExecuteSql("insert into SysProjectRole select RoleID,@ProjectID from SysRole where ','+@Roles+',' like '%,'+cast(RoleID as nvarchar(36))+',%'", new SqlParameter[] { new SqlParameter("@ProjectID", ProjectID), new SqlParameter("@Roles", Roles) });
            return Json(new { code = 0 });


        }
        #endregion
        #region 获取界面名称
        [HttpPost]
        public JsonResult getInterface()
        {
            QuerySuite querySuite = new QuerySuite("sysApi where description='1' and IsNeedPermisson='1'", "distinct interface");

            DataSet ds = SqlHelper.Query(querySuite.LimitSql, querySuite.Params);

            return Json(new { code = 0, data = QuerySuite.ToDictionary(ds.Tables[0]), count = QuerySuite.DsCount(ds) });

        }
        [HttpPost]
        public JsonResult getInterfaceButton(string Interface)
        {
            QuerySuite querySuite = new QuerySuite("sysApi where description='1' and PageUrl=@Interface and IsNeedPermisson='1' or UrlAddr=''", "distinct ApiName,ButtonID");
            querySuite.AddParam("Interface", Interface);

            DataSet ds = SqlHelper.Query(querySuite.LimitSql, querySuite.Params);

            return Json(new { code = 0, data = QuerySuite.ToDictionary(ds.Tables[0]), count = QuerySuite.DsCount(ds) });

        }

        /// <summary>
        /// 查询页面按钮权限
        /// </summary>
        /// <param name="Interface"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult GetInterfacePermission(string Interface)
        {
            // 查出与当前页面所有相关的按钮
            BaseFreeSqlDao<sysApiModel> sysApiDao = new BaseFreeSqlDao<sysApiModel>();
            List<sysApiModel> sysApiModels = sysApiDao.GetList(t => t.PageUrl == Interface && (t.description == "1" || t.description == "2"));



            // 如果是开发运维角色则不验证是否有按钮权限
            if (userInfo.DefaultRoleID.ToString().ToUpper() == HttpContextCore.developID)
            {
                foreach (var item in sysApiModels)
                {
                    item.isshow = "是";
                }
                return Json(new { code = 0, data = sysApiModels.Select(t => new { t.ButtonID, t.isshow, t.description }) });

            }
            else
            {
                BaseFreeSqlDao<RoleAPIMappingModel> roleApimappingDao = new BaseFreeSqlDao<RoleAPIMappingModel>();
                List<RoleAPIMappingModel> roleAPIMappingModels = roleApimappingDao.GetList(t => t.RoleId == userInfo.DefaultRoleID.ToString());
                List<RoleAPIMappingModel> roleAPIMappingModels1 = roleApimappingDao.GetList(t => t.UserId == userInfo.UserID.ToString());
                roleAPIMappingModels.AddRange(roleAPIMappingModels1);

                foreach (var item in sysApiModels)
                {
                    if (!item.IsNeedPermisson) //如果不需要权限，则直接显示 内置的按钮
                    {
                        item.isshow = "是";
                        continue;
                    }
                    if (roleAPIMappingModels.Any(t => t.ApiId == item.ID))
                    {
                        item.isshow = "是";
                    }
                    else
                    {
                        item.isshow = "否";
                    }

                }
                return Json(new { code = 0, data = sysApiModels.Select(t => new { t.ButtonID, t.isshow, t.description }) });
            }
        }
        #endregion

        public string ConvertToSqlInStr(IList<string> list)
        {
            var sb = new StringBuilder();
            foreach (var t in list)
            {
                sb.Append("'");
                sb.Append(t);
                sb.Append("'");
                sb.Append(",");
            }
            if (sb.Length > 0)
                sb.Remove(sb.Length - 1, 1);

            return sb.ToString();
        }
        #region
        public JsonResult getProjectRoleList(string ID, Search search)
        {
            QuerySuite querySuite = new QuerySuite("SysRole a left join SysProjectRole b on a.RoleID=b.RoleID and b.ProjectID=@ProjectID", "distinct a.RoleID,a.RoleName,a.Remarks,case when b.ProjectID is not null then 1 else 0 end LAY_CHECKED ", search);
            querySuite.AddParam("ProjectID", ID);
            DataSet ds = SqlHelper.Query(querySuite.LimitSql, querySuite.Params);
            return Json(new { code = 0, data = QuerySuite.ToDictionary(ds.Tables[0]), count = QuerySuite.DsCount(ds) });

        }
        #endregion

        /// <summary>
        ///获取项目对应的角色
        /// </summary>
        /// <param name="search"></param>
        /// <returns></returns>
        public JsonResult getRoleListByProject(string projectNo, Search search)
        {
            QuerySuite querySuite = new QuerySuite("SysRole a left join SysProjectRole b on a.RoleID=b.RoleID left join SysProject c on b.ProjectID=c.No and c.ProjectNo=@ProjectNo", "distinct a.RoleID,a.RoleName,c.ProjectNo ", search);
            querySuite.AddParam("ProjectNo", projectNo);
            DataSet ds = SqlHelper.Query(querySuite.LimitSql, querySuite.Params);
            return Json(new { code = 0, data = QuerySuite.ToDictionary(ds.Tables[0]), count = QuerySuite.DsCount(ds) });

        }



        #region 角色和人员权限管理
        [HttpPost]
        public JsonResult getRolePeopleList()
        {
            QuerySuite querySuite = new QuerySuite("SysRole a left join SysProjectRole b on a.RoleID=b.RoleID");
            querySuite.Order = "RoleName";
            if (userInfo.project.ToUpper() != "")
            {
                querySuite.AddParam("ProjectID", "=", userInfo.project);
            }

            DataSet ds = SqlHelper.Query(querySuite.LimitSql, querySuite.Params);

            DataSet users = SqlHelper.Query("SELECT * FROM  SysUser where RecordStatus =0");
            List<SysUser> userlist = ModelHelper<SysUser>.ConvertToModelList(users.Tables[0]);
            List<dynamic> list = new List<dynamic>();
            for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
            {
                dynamic model = new
                {
                    ID = ds.Tables[0].Rows[i]["RoleID"].ToString(),
                    Name = ds.Tables[0].Rows[i]["RoleName"].ToString(),
                    Type = 1,
                    ParentId = ""
                };
                list.Add(model);
                foreach (var item in userlist)
                {
                    if (item.DefaultRoleID.ToString() == ds.Tables[0].Rows[i]["RoleID"].ToString())
                    {
                        model = new
                        {
                            ID = item.UserID,
                            Name = item.UserName,
                            Type = 2,
                            ParentId = ds.Tables[0].Rows[i]["RoleID"].ToString()
                        };
                        list.Add(model);
                    }
                }
            }

            return Json(new { code = 0, data = list });

        }

        [HttpPost]
        public JsonResult getRolePeoplePageList(Guid? RoleID, Guid? UserId)
        {

            if (UserId.HasValue)
            {
                BaseFreeSqlDao<SysUser> sysuserDao = new BaseFreeSqlDao<SysUser>();
                SysUser sysUser = sysuserDao.GetByOne(t => t.UserID == UserId && t.RecordStatus == false);

                QuerySuite querySuite = new QuerySuite("SysPage a left join SysRolePage b on a.PageID=b.PageID and b.RoleID=@RoleID ", "distinct a.PageID,a.ParentID,a.PageName,a.PageName_EN,a.PageType,a.PageUrl,OrderNo,case when b.PageID is not null then 1 else 0 end lay_is_checked ");
                querySuite.AddParam("RoleID", sysUser.DefaultRoleID);


                DataSet ds = SqlHelper.Query(querySuite.LimitSql, querySuite.Params);
                List<RolePeoplePageModedl> list = ModelHelper<RolePeoplePageModedl>.ConvertToModelList(ds.Tables[0]);

                querySuite = new QuerySuite("SysPage a left join SysUserPage b on a.PageID=b.PageID and b.UserID=@UserID ", "distinct a.PageID,a.ParentID,a.PageName,a.PageName_EN,a.PageType,a.PageUrl,OrderNo,case when b.PageID is not null then 1 else 0 end lay_is_checked ");
                querySuite.AddParam("UserID", UserId);

                ds = SqlHelper.Query(querySuite.LimitSql, querySuite.Params);
                IList<RolePeoplePageModedl> list1 = ModelHelper<RolePeoplePageModedl>.ConvertToModelList(ds.Tables[0]);
                foreach (var item in list1)
                {
                    RolePeoplePageModedl rolePeoplePageModedl = list.Where(t => t.PageID == item.PageID).FirstOrDefault();
                    if (rolePeoplePageModedl != null)
                    {
                        if (item.lay_is_checked == 1)
                        {
                            rolePeoplePageModedl.lay_is_checked = 1;
                        }

                        continue;
                    }
                    list.Add(item);
                }


                BaseFreeSqlDao<sysApiModel> sysApiDao = new BaseFreeSqlDao<sysApiModel>();
                List<sysApiModel> sysApiModels = sysApiDao.GetList(t => t.description == "1" || t.description == "2");

                BaseFreeSqlDao<RoleAPIMappingModel> roleApiMapping = new BaseFreeSqlDao<RoleAPIMappingModel>();
                List<RoleAPIMappingModel> roleAPIMappingModels = roleApiMapping.GetList(t => t.UserId == UserId.ToString());

                List<RolePeoplePageModedl> customizePage = list.Where(t => t.PageUrl.IsNotNullOrEmpty()).ToList();
                foreach (var item in customizePage)
                {
                    foreach (var item1 in sysApiModels)
                    {
                        var arr = item.PageUrl.Split('/');
                        if (arr[arr.Length - 1].ToLower() == item1.PageUrl.ToLower())
                        {
                            RolePeoplePageModedl rolePeoplePageModedl = new RolePeoplePageModedl
                            {
                                PageID = item1.ID.ToGuid(),
                                lay_is_checked = roleAPIMappingModels.Any(t => t.ApiId == item1.ID) ? 1 : 0,
                                PageName = item1.ApiName,
                                PageName_EN = item1.ButtonID,
                                PageType = int.Parse(item1.description) == (int)ButtonTypeEnum.PageBtn ? ButtonTypeEnum.PageBtn.ToString() : ButtonTypeEnum.ColBtn.ToString(),
                                PageUrl = item1.PageUrl,
                                ParentID = item.PageID
                            };
                            list.Add(rolePeoplePageModedl);
                        }
                    }
                }



                return Json(new { code = 0, data = list, count = list.Count() });
            }
            else if (RoleID.HasValue)
            {
                QuerySuite querySuite = new QuerySuite("SysPage a left join SysRolePage b on a.PageID=b.PageID and cast(b.RoleID as varchar(36))=@RoleID ", "distinct a.PageID,a.ParentID,a.PageName,a.PageName_EN,a.PageType,a.PageUrl,OrderNo,case when b.PageID is not null then 1 else 0 end lay_is_checked ");
                querySuite.AddParam("RoleID", RoleID.ToString());


                DataSet ds = SqlHelper.Query(querySuite.LimitSql, querySuite.Params);

                List<RolePeoplePageModedl> list = ModelHelper<RolePeoplePageModedl>.ConvertToModelList(ds.Tables[0]);

                BaseFreeSqlDao<sysApiModel> sysApiDao = new BaseFreeSqlDao<sysApiModel>();
                List<sysApiModel> sysApiModels = sysApiDao.GetList(t => t.description == "1" || t.description == "2");

                BaseFreeSqlDao<RoleAPIMappingModel> roleApiMapping = new BaseFreeSqlDao<RoleAPIMappingModel>();
                List<RoleAPIMappingModel> roleAPIMappingModels = roleApiMapping.GetList(t => t.RoleId == RoleID.ToString());

                List<RolePeoplePageModedl> customizePage = list.Where(t => t.PageUrl.IsNotNullOrEmpty()).ToList();
                foreach (var item in customizePage)
                {
                    foreach (var item1 in sysApiModels)
                    {
                        var arr = item.PageUrl.Split('/');
                        if (arr[arr.Length - 1].ToLower() == item1.PageUrl.ToLower())
                        {
                            RolePeoplePageModedl rolePeoplePageModedl = new RolePeoplePageModedl
                            {
                                PageID = item1.ID.ToGuid(),
                                lay_is_checked = roleAPIMappingModels.Any(t => t.ApiId == item1.ID) ? 1 : 0,
                                PageName = item1.ApiName,
                                PageName_EN = item1.ButtonID,
                                PageType = int.Parse(item1.description) == (int)ButtonTypeEnum.PageBtn ? ButtonTypeEnum.PageBtn.ToString() : ButtonTypeEnum.ColBtn.ToString(),

                                PageUrl = item1.PageUrl,
                                ParentID = item.PageID
                            };
                            list.Add(rolePeoplePageModedl);
                        }
                    }
                }

                return Json(new { code = 0, data = list, count = list.Count });
            }
            else
            {
                QuerySuite querySuite = new QuerySuite("SysPage a left join SysRolePage b on a.PageID=b.PageID and b.RoleID=@RoleID ", "distinct a.PageID,a.ParentID,a.PageName,a.PageName_EN,a.PageType,a.PageUrl,OrderNo,case when b.PageID is not null then 1 else 0 end lay_is_checked ");
                querySuite.AddParam("RoleID", userInfo.DefaultRoleID.ToString());

                DataSet ds = SqlHelper.Query(querySuite.LimitSql, querySuite.Params);

                List<RolePeoplePageModedl> list = ModelHelper<RolePeoplePageModedl>.ConvertToModelList(ds.Tables[0]);

                BaseFreeSqlDao<sysApiModel> sysApiDao = new BaseFreeSqlDao<sysApiModel>();
                List<sysApiModel> sysApiModels = sysApiDao.GetList(t => t.description == "1" || t.description == "2");

                List<RolePeoplePageModedl> customizePage = list.Where(t => t.PageUrl.IsNotNullOrEmpty()).ToList();
                foreach (var item in customizePage)
                {
                    foreach (var item1 in sysApiModels)
                    {
                        var arr = item.PageUrl.Split('/');
                        if (arr[arr.Length - 1].ToLower() == item1.PageUrl.ToLower())
                        {
                            RolePeoplePageModedl rolePeoplePageModedl = new RolePeoplePageModedl
                            {
                                PageID = item1.ID.ToGuid(),
                                lay_is_checked = 0,
                                PageName = item1.ApiName,
                                PageName_EN = item1.ButtonID,
                                PageType = int.Parse(item1.description) == (int)ButtonTypeEnum.PageBtn ? ButtonTypeEnum.PageBtn.ToString() : ButtonTypeEnum.ColBtn.ToString(),

                                PageUrl = item1.PageUrl,
                                ParentID = item.PageID
                            };
                            list.Add(rolePeoplePageModedl);
                        }
                    }
                }




                return Json(new { code = 0, data = list, count = list.Count });

            }


        }

        [HttpPost]
        public JsonResult saveRolePeoplePage([FromBody] RolePeoplePageParams rolePeoplePageParams)
        {
            if (rolePeoplePageParams.UserId.HasValue)
            {
                SqlHelper.ExecuteSql("delete SysUserPage where UserID=@UserID", new SqlParameter("@UserID", rolePeoplePageParams.UserId));
                SqlHelper.ExecuteSql("delete RoleAPIMapping where UserId=@UserID and Type = 2", new SqlParameter("@UserID", rolePeoplePageParams.UserId));

                if (!string.IsNullOrEmpty(rolePeoplePageParams.Roles))
                    SqlHelper.ExecuteSql("insert into SysUserPage select @UserID,PageID from SysPage where ','+@Roles+',' like '%,'+cast(PageID as nvarchar(36))+',%'", new SqlParameter[] { new SqlParameter("@UserID", rolePeoplePageParams.UserId), new SqlParameter("@Roles", rolePeoplePageParams.Roles) });
            }
            else
            {

                SqlHelper.ExecuteSql("delete SysRolePage where RoleID=@RoleID", new SqlParameter("@RoleID", rolePeoplePageParams.RoleID));
                SqlHelper.ExecuteSql("delete RoleAPIMapping where RoleId=@RoleID and Type = 2", new SqlParameter("@RoleID", rolePeoplePageParams.RoleID.ToString()));

                if (!string.IsNullOrEmpty(rolePeoplePageParams.Roles))
                    SqlHelper.ExecuteSql("insert into SysRolePage select @RoleID,PageID from SysPage where ','+@Roles+',' like '%,'+cast(PageID as nvarchar(36))+',%'", new SqlParameter[] { new SqlParameter("@RoleID", rolePeoplePageParams.RoleID), new SqlParameter("@Roles", rolePeoplePageParams.Roles) });




            }

            BaseFreeSqlDao<RoleAPIMappingModel> sysInterfacePermissionFreeSqlDao = new BaseFreeSqlDao<RoleAPIMappingModel>();
            foreach (var item in rolePeoplePageParams.ButtonAuthority)
            {
                item.Id = Guid.NewGuid().ToString();
                item.RecordStatus = false;
                item.CreateOn = DateTime.Now;
                item.CeateBy = SSOClient.getUser(HttpContext).UserID.ToString();
                item.Type = 2;
            }
            sysInterfacePermissionFreeSqlDao.BatchInsert(rolePeoplePageParams.ButtonAuthority);



            return Json(new { code = 0 });
        }
        #endregion
    }
}